#include "VTKModelStudioMainWindow.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QTimer>
#include <QFileDialog>
#include <QRandomGenerator>


VTKModelStudioMainWindow::VTKModelStudioMainWindow(QWidget* parent) : ElaWindow(parent)
{
    QString appName = "VTKModel";
    setWindowTitle(appName);
    setNavigationBarDisplayMode(ElaNavigationType::Compact);
    setUserInfoCardVisible(false);
    setFocusPolicy(Qt::StrongFocus);
    setAppBarHeight(30);

     setIsAllowPageOpenInNewWindow(true); // 设置可以在新窗口打开

    // 设置窗口按钮标志
    setWindowButtonFlags(ElaAppBarType::StayTopButtonHint | ElaAppBarType::MinimizeButtonHint | ElaAppBarType::MaximizeButtonHint | ElaAppBarType::CloseButtonHint | ElaAppBarType::ThemeChangeButtonHint);

    // 创建随机转动定时器
    m_randomRotationEnabled = false;
    m_randomRotationTimer = new QTimer(this);
    m_randomRotationTimer->setInterval(50);  // 50毫秒间隔
    connect(m_randomRotationTimer, &QTimer::timeout, this, &VTKModelStudioMainWindow::updateRandomRotation);

    setupUI();
    setupConnections();
}

VTKModelStudioMainWindow::~VTKModelStudioMainWindow()
{
    // 确保定时器停止
    if (m_randomRotationTimer && m_randomRotationTimer->isActive())
    {
        m_randomRotationTimer->stop();
    }
}

void VTKModelStudioMainWindow::setupToolBar()
{
    // 创建工具栏
    m_toolBar = new ElaToolBar("模型工具栏", this);
    m_toolBar->setAllowedAreas(Qt::TopToolBarArea | Qt::BottomToolBarArea);
    m_toolBar->setToolBarSpacing(3);
    m_toolBar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
    m_toolBar->setIconSize(QSize(25, 25));

    // 打开模型文件按钮
    m_openButton = new ElaToolButton(this);
    m_openButton->setElaIcon(ElaIconType::FolderOpen);
    m_openButton->setToolTip("打开模型文件");
    m_toolBar->addWidget(m_openButton);
    connect(m_openButton, &ElaToolButton::clicked, this, &VTKModelStudioMainWindow::onOpenModel);

    // 关闭模型文件按钮
    m_closeButton = new ElaToolButton(this);
    m_closeButton->setElaIcon(ElaIconType::XmarkLarge);
    m_closeButton->setToolTip("关闭模型文件");
    m_toolBar->addWidget(m_closeButton);
    connect(m_closeButton, &ElaToolButton::clicked, this, &VTKModelStudioMainWindow::onCloseModel);

    m_toolBar->addSeparator();

    // 截图按钮
    m_screenshotButton = new ElaToolButton(this);
    m_screenshotButton->setElaIcon(ElaIconType::Camera);
    m_screenshotButton->setToolTip("截图");
    m_toolBar->addWidget(m_screenshotButton);
    connect(m_screenshotButton, &ElaToolButton::clicked, this, &VTKModelStudioMainWindow::onScreenshot);

    m_toolBar->addSeparator();

    // 加载默认STL按钮
    m_loadSTLButton = new ElaToolButton(this);
    m_loadSTLButton->setElaIcon(ElaIconType::Cube);
    m_loadSTLButton->setText("加载STL");
    m_loadSTLButton->setToolTip("加载默认STL模型");
    m_toolBar->addWidget(m_loadSTLButton);
    connect(m_loadSTLButton, &ElaToolButton::clicked, this, &VTKModelStudioMainWindow::onLoadDefaultSTL);

    // 加载默认MOD按钮
    m_loadMODButton = new ElaToolButton(this);
    m_loadMODButton->setElaIcon(ElaIconType::Cubes);
    m_loadMODButton->setText("加载MOD");
    m_loadMODButton->setToolTip("加载默认MOD模型");
    m_toolBar->addWidget(m_loadMODButton);
    connect(m_loadMODButton, &ElaToolButton::clicked, this, &VTKModelStudioMainWindow::onLoadDefaultMOD);

    // 加载默认OBJ按钮
    m_loadOBJButton = new ElaToolButton(this);
    m_loadOBJButton->setElaIcon(ElaIconType::CubesStacked);
    m_loadOBJButton->setText("加载OBJ");
    m_loadOBJButton->setToolTip("加载默认OBJ模型");
    m_toolBar->addWidget(m_loadOBJButton);
    connect(m_loadOBJButton, &ElaToolButton::clicked, this, &VTKModelStudioMainWindow::onLoadDefaultOBJ);
    
    m_toolBar->addSeparator();
    m_randomRotationButton = new ElaToolButton(this);
    m_randomRotationButton->setElaIcon(ElaIconType::Rotate);  // 使用旋转图标
    m_randomRotationButton->setText("随机转动");
    m_randomRotationButton->setToolTip("开始/停止随机转动模型 (50ms间隔)");
    //m_randomRotationButton->setCheckable(true);  // 设置为可切换状态
    m_toolBar->addWidget(m_randomRotationButton);
    connect(m_randomRotationButton, &ElaToolButton::clicked, this, &VTKModelStudioMainWindow::onRandomRotation);


    // 将工具栏添加到窗口
    this->addToolBar(Qt::TopToolBarArea, m_toolBar);
}

void VTKModelStudioMainWindow::setupUI()
{
    setupToolBar();

    // 直接创建VTK模型工作室
    m_studio = new VTKModelStudio(this);
    m_studio->setMouseInteractionEnabled(true);


    std::string dataDir = DEFAULT_AO_DATA_DIR;
    //QString inputFilename = QString::fromStdString(dataDir + "/ExampleSTL.stl");
    //QString inputFilename = "D:/work/vvlai/file/model/ROV_600_model/600K.stl";
    //QString inputFilename = "D:/work/vvlai/file/model/ROV_40_model/ROV40.stl";
    QString inputFilename = "D:/work/vvlai/file/model/ROV_900_model/ROV900.stl";

    std::string modelFileName = inputFilename.toUtf8().constData();

    m_studio->loadModel(modelFileName);
    m_studio->setAttitudeMarkerVisible(true);

    //// 显示坐标轴
    //m_studio->setAxesWorldVisible(false);
    //m_studio->setCompassVisible(true);
    // 600参数
    //// 设置罗盘位置
    //m_studio->compass->setVisible(true);
    //m_studio->compass->setPosition(0, 0, -0.2);
    //m_studio->compass->setScale(1.0);
    ////m_studio->compass->setDiskColor(Qt::darkGray);
    //m_studio->compass->setDiskColor(QColor("#566573"));
    //m_studio->compass->setTextAndLineColor(QColor("#E74C3C"));
    //m_studio->compass->setDiskOpacity(0.5);
    //m_studio->compass->setTextAndLineOpacity(1.0);
    //m_studio->compass->setDiskRadius(0.4, 0.5);
    //m_studio->compass->setLineWidth(3.0);
    ////// 修改相机的位置
    //m_studio->setCameraFocalPoint(0, 0, 0);
    //m_studio->setCameraPosition(-3, 0, 2);
    //m_studio->setCameraViewUp(0, 0, 1);
    //// 设置光源
    //m_studio->setLightPosition(4, 4, 4);
    //m_studio->setLightFocalPoint(0, 0, 0);
    //m_studio->setLightIntensity(0.5);
    //m_studio->setLightEnabled(true);  // 再开启

    //// 40参数
    //// 设置罗盘位置
    //m_studio->compass->setVisible(true);
    //m_studio->compass->setPosition(0, 0, -15);
    //m_studio->compass->setScale(1.0);
    //// m_studio->compass->setDiskColor(Qt::darkGray);
    //m_studio->compass->setDiskColor(QColor("#566573"));
    //m_studio->compass->setTextAndLineColor(QColor("#E74C3C"));
    //m_studio->compass->setDiskOpacity(0.5);
    //m_studio->compass->setTextAndLineOpacity(1.0);
    //m_studio->compass->setDiskRadius(40, 55);
    //m_studio->compass->setLineWidth(3.0);
    ////// 修改相机的位置
    //m_studio->setCameraFocalPoint(0, 0, 0);
    //m_studio->setCameraPosition(-30, 0, 20);
    //m_studio->setCameraViewUp(0, 0, 1);
    //// 设置光源
    //m_studio->setLightPosition(4, 4, 4);
    //m_studio->setLightFocalPoint(0, 0, 0);
    //m_studio->setLightIntensity(0.5);
    //m_studio->setLightEnabled(true);  // 再开启

    // 800/900参数
    // 设置罗盘位置
    m_studio->compass->setVisible(true);
    m_studio->compass->setPosition(0, 0, -20);
    m_studio->compass->setScale(1.0);
    // m_studio->compass->setDiskColor(Qt::darkGray);
    m_studio->compass->setDiskColor(QColor("#566573"));
    m_studio->compass->setTextAndLineColor(QColor("#E74C3C"));
    m_studio->compass->setDiskOpacity(0.5);
    m_studio->compass->setTextAndLineOpacity(1.0);
    m_studio->compass->setDiskRadius(40, 55);
    m_studio->compass->setLineWidth(3.0);
    //// 修改相机的位置
    m_studio->setCameraFocalPoint(0, 0, 0);
    m_studio->setCameraPosition(-20, 0, 10);
    m_studio->setCameraViewUp(0, 0, 1);
    // 设置光源
    m_studio->setLightPosition(4, 4, 4);
    m_studio->setLightFocalPoint(0, 0, 0);
    m_studio->setLightIntensity(0.5);
    m_studio->setLightEnabled(true);  // 再开启
    m_studio->zoomCamera(1.5);        // 直接调用类方法放大3倍

    // 创建页面
    m_vtkPage = new QWidget(this);
    // 设置背景颜色 - 橙色背景用于测试透明度
    m_vtkPage->setStyleSheet("background-color: #DC7633;");

    QVBoxLayout* layout = new QVBoxLayout(m_vtkPage);
    layout->addWidget(m_studio);
    layout->setContentsMargins(0, 0, 0, 0);
    layout->setSpacing(0);

    addPageNode("3D模型", m_vtkPage, ElaIconType::Display);

    m_settingPage = new SettingPage(this, m_studio);
    QString _settingKey{""};
    addFooterNode(tr("设置"), nullptr, _settingKey, 0, ElaIconType::GearComplex);
    m_settingPage->hide();
    connect(this, &ElaWindow::navigationNodeClicked, this, [=](ElaNavigationType::NavigationNodeType nodeType, QString nodeKey) {
        if (_settingKey == nodeKey)
        {
            m_settingPage->setMinimumSize(800, 1000);
            m_settingPage->moveToCenter();
            m_settingPage->show();
        }
    });
}

void VTKModelStudioMainWindow::setupConnections()
{
    // 连接信号
    //connect(m_studio, &VTKModelStudio::errorOccurred, this, &VTKModelStudioMainWindow::onErrorOccurred);
}

void VTKModelStudioMainWindow::onOpenModel()
{
    QString fileName = QFileDialog::getOpenFileName(this, "打开模型文件", "", "3D模型文件 (*.stl *.obj *.mod *.ply *.vtk *.vtp)");
    if (!fileName.isEmpty())
    {
        std::string modelFileName = fileName.toUtf8().constData();
        m_studio->loadModel(modelFileName);
    }
    // 如果随机转动正在运行，更新按钮状态
    if (m_randomRotationEnabled)
    {
        m_randomRotationButton->setChecked(true);
    }
}

void VTKModelStudioMainWindow::onCloseModel()
{
    // 清除当前模型
    if (m_studio)
    {
        m_studio->clearModel();

        // 如果随机转动正在运行，停止它
        if (m_randomRotationEnabled)
        {
            onRandomRotation();  // 切换状态
        }
    }
}

void VTKModelStudioMainWindow::onScreenshot()
{
}

void VTKModelStudioMainWindow::onLoadDefaultSTL()
{
    if (m_studio)
    {
        std::string dataDir = DEFAULT_AO_DATA_DIR;
        QString inputFilename = QString::fromStdString(dataDir + "/ExampleSTL.stl");
        std::string modelFileName = inputFilename.toUtf8().constData();
        m_studio->loadModel(modelFileName);

        // 如果随机转动正在运行，更新按钮状态
        if (m_randomRotationEnabled)
        {
            m_randomRotationButton->setChecked(true);
        }
    }
}

void VTKModelStudioMainWindow::onLoadDefaultMOD()
{
    if (m_studio)
    {
        std::string dataDir = DEFAULT_AO_DATA_DIR;
        QString inputFilename = QString::fromStdString(dataDir + "/ExampleModel.mod");
        std::string modelFileName = inputFilename.toUtf8().constData();
        m_studio->loadModel(modelFileName);

        // 如果随机转动正在运行，更新按钮状态
        if (m_randomRotationEnabled)
        {
            m_randomRotationButton->setChecked(true);
        }
    }
}

void VTKModelStudioMainWindow::onLoadDefaultOBJ()
{
    if (m_studio)
    {
        std::string dataDir = DEFAULT_AO_DATA_DIR;
        QString inputFilename = QString::fromStdString(dataDir + "/ExampleOBJ.obj");
        std::string modelFileName = inputFilename.toUtf8().constData();
        m_studio->loadModel(modelFileName);

        // 如果随机转动正在运行，更新按钮状态
        if (m_randomRotationEnabled)
        {
            m_randomRotationButton->setChecked(true);
        }
    }
}


void VTKModelStudioMainWindow::onRandomRotation()
{
    if (!m_studio || !m_studio->isModelLoaded())
    {
        // 没有加载模型时，禁用按钮并提示
        m_randomRotationButton->setChecked(false);
        qWarning() << "请先加载模型再启动随机转动";
        return;
    }

    m_randomRotationEnabled = !m_randomRotationEnabled;

    if (m_randomRotationEnabled)
    {
        // 开始随机转动
        m_randomRotationTimer->start();
        m_randomRotationButton->setText("停止转动");
        m_randomRotationButton->setToolTip("停止随机转动");
        qDebug() << "开始随机转动，间隔50ms";
    }
    else
    {
        // 停止随机转动
        m_randomRotationTimer->stop();
        m_randomRotationButton->setText("随机转动");
        m_randomRotationButton->setToolTip("开始随机转动模型 (50ms间隔)");
        qDebug() << "停止随机转动";
    }
}

// 执行随机转动更新
void VTKModelStudioMainWindow::updateRandomRotation()
{
    if (!m_studio || !m_studio->isModelLoaded())
    {
        if (m_randomRotationTimer->isActive())
        {
            m_randomRotationTimer->stop();
            m_randomRotationEnabled = false;
            m_randomRotationButton->setChecked(false);
            m_randomRotationButton->setText("随机转动");
        }
        return;
    }

    // 生成随机的航向、俯仰、横滚角度（-180到180度）
    double yaw = QRandomGenerator::global()->bounded(-1800, 1800) / 10.0;
    double pitch = QRandomGenerator::global()->bounded(-1800, 1800) / 10.0;
    double roll = QRandomGenerator::global()->bounded(-1800, 1800) / 10.0;

    // 设置模型旋转
    m_studio->setModelRotation(yaw, pitch, roll);

    // 可选：输出当前角度（调试用，高频时建议注释掉）
    // qDebug() << QString("随机角度 - 航向: %1°, 俯仰: %2°, 横滚: %3°").arg(yaw, 0, 'f', 1).arg(pitch, 0, 'f', 1).arg(roll, 0, 'f', 1);
}